package com.yuting.user.controller;

import com.yuting.common.pojo.Token;
import com.yuting.user.dao.TokenDao;
import lagou.service.dubbo.api.RpcCodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("user")
@RefreshScope
public class UserController {

    @Value("${test.haha}")
    private String port;


    @Autowired
    private TokenDao tokenDao;

    @Reference
    private RpcCodeService rpcCodeService;

    @GetMapping("/test")
    public String test(){
        return "hello!  " + port;
    }


    @GetMapping("/register/{email}/{password}/{code}")

    public boolean register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code, HttpServletResponse response){
        Integer integer = rpcCodeService.codeValidate(email, code);

        if(integer == 0){
            Token token = new Token();
            token.setEmail(email);
            token.setToken(UUID.randomUUID().toString());
            tokenDao.save(token);
            Cookie cookie = new Cookie("token", token.getToken());
            response.addCookie(cookie);
            return true;
        }else {
            return false;
        }
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email){
        Token byEmailEquals = tokenDao.findByEmailEquals(email);
        if(byEmailEquals != null){
            return true;
        }else {
            return false;
        }
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response){
        Token token = new Token();
        token.setEmail(email);
        token.setToken(UUID.randomUUID().toString());
        tokenDao.save(token);
        Cookie cookie = new Cookie("token", token.getToken());
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);

        return email;
    }

    @GetMapping("/info/{token}")
    public String userInfo(@PathVariable("token")String token){
        Token byTokenEquals = tokenDao.findByTokenEquals(token);
        if(byTokenEquals != null){
            return byTokenEquals.getEmail();
        }else{
            return "error";
        }
    }
}
